import LoginApi from '@/api/login';
import {
	ref,
	onBeforeUnmount
}
from 'vue'
export function useSendCode() {
	let codeDisabled = ref(false);
	let codeLoading = ref(false);
	let codeText = ref("获取验证码");
	let codeDuration = ref(60);
	let timer = null;

	function getCode(mobile, payload) {
		const phoneReg = /^[1][3456789][0-9]{9}$/;
		if (codeDisabled.value) return;
		if (!phoneReg.test(mobile)) {
			uni.showToast({
				title: '请输入正确的验证码',
				icon: 'none'
			})
		}
		else {
			uni.showLoading({
				title: '发送中',
				mask: true
			})
			codeLoading.value = true;
			LoginApi.sendCode(payload)
				.then(() => {
					codeLoading.value = false;
					codeDisabled.value = true;
					codeText.value = `重新获取(${codeDuration.value})`;
					startTime();
					uni.showToast({
						title: `验证码已发至${mobile},请注意查收！`
					})
				})
				.catch(() => {
					codeText.value = "获取验证码";
					codeLoading.value = false;
				});
		}
	}

	function startTime() {
		timer = setInterval(() => {
			codeDuration.value = codeDuration.value - 1;
			codeText.value = `重新获取(${codeDuration.value})`;
			if (codeDuration.value === 0) {
				clearInterval(timer);
				init();
			}
		}, 1000);
	}

	function init() {
		codeDisabled.value = false;
		codeLoading.value = false;
		codeText.value = "获取验证码";
		codeDuration.value = 60;
	}
	onBeforeUnmount(() => {
		clearInterval(timer);
		init();
	});
	return {
		getCode,
		codeLoading,
		codeDisabled,
		codeText,
	};
}